import { url } from "./url.js"
export default{
	// 全局配置
	common:{
		baseUrl: url,
		header:{
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},
		data:{},
		method:'GET',
		dataType:'json'
	},
	
	// 请求 返回promise
	request(options = {}){
		// 组织参数
		options.url = this.common.baseUrl + options.url
		options.header = options.header || this.common.header
		options.data = options.data || this.common.data
		options.method = options.method || this.common.method
		options.dataType = options.dataType || this.common.dataType
		
		let token = uni.getStorageSync("token");
		if(token) options.data.token = token
		
		// 请求
		return new Promise((res,rej)=>{
			// 请求之前... todo
			// 请求中...
			uni.showLoading({title: "加载中", mask: true})
			uni.request({
				...options,
				success: (result) => {
					uni.hideLoading()
					if(result.statusCode == 401) {
						uni.clearStorageSync()
						setTimeout(()=>{
							uni.reLaunch({
								url: "/pages/login/login"
							})
						},1000)
						uni.showToast({ title: "请登录", icon: "none",duration:1000})
						return
					}
					if(result.statusCode == 200) {
						res(result.data)
					}
				},
				fail: (error) => {
					uni.hideLoading()
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					return rej()
				}
			});
		}).catch((e)=>{});
	},
	// get请求
	get(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// delete请求
	del(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
	// options请求
	options(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'options'
		return this.request(options)
	},
	// put请求
	put(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'put'
		return this.request(options)
	},
	// head请求
	head(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'head'
		return this.request(options)
	},
	// trace请求
	trace(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'trace'
		return this.request(options)
	},
	// connect请求
	connect(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'connect'
		return this.request(options)
	},
}
